InsDateSet = new Object();

InsDateSet.getFieldSet1 = function() {
	
	var actionStore = Ext.create('Ext.data.Store', {
		fields	:	[	{ name : 'action',		type : 'string'	} ],
		data	:	[	{ "action" : "Floating Rate Reset"		},
		    	 	 	{ "action" : "Coupon Date Reset"		}
		    	 	]
	});
	
	Ext.create('Ext.data.Store', {
		fields : [
		          { name : 'id',			type : 'int',		},
		          { name : 'fundName',		type : 'string',	},
		          {	name : 'fundCode',		type : 'string',	},
		          {	name : 'updateDate',	type : 'date',		dateFormat : 'c'	}
		         ],
		storeId:'insDateSetFundStore',
		});
	
	Ext.Ajax.request({
		url : 'getFundNames.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.data.StoreManager.lookup('insDateSetFundStore').loadRawData(obj.fundList);
		},
		failure : function(response){
			Ext.Msg.alert('Error!', 'Failed to load Fund List : '+response);
		},
	});
	
	new Ext.data.Store({
		fields : [ {	name : 'id',					type : 'int'	},
		           {	name : 'instrumentName',		type : 'string'	},
		           {	name : 'interestRate',			type : 'string'	},
		           {	name : 'couponAvailability',	type : 'int'	}
		         ],
		storeId:'insDateSetInsTypeStore',
	});
	
	new Ext.data.Store({
		fields : [ {	name : 'id',				type : 'int'	},
		           {	name : 'instrumentCode',	type : 'string'	},
		           {	name : 'instrumentType',	type : 'string'	},
		           {	name : 'issueDate',			type : 'date',		dateFormat : 'c'	},
		           {	name : 'maturityDate',		type : 'date',		dateFormat : 'c'	}
		         ],
		storeId:'insDateSetInsCodeStore',
	});

	
	
	var fieldSet1 = Ext.create('Ext.form.FieldSet', {
		//title : 'Basic',
		defaults : {
			anchor : '100%'
		},
		items : [
		{
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ 
			 {
	        	 xtype : 'combo',
	        	 name : 'fundId',
	        	 fieldLabel : 'Fund',
	        	 store : Ext.data.StoreManager.lookup('insDateSetFundStore'),
	        	 valueField : 'id',
	        	 queryMode : 'local',
	        	 flex : 1,
	        	 id : 'insDateSetFundCmb',
	        	 padding : '0 5 0 5',
	        	 autoScroll : false,
	        	 allowBlank : false,
	        	 msgTarget : 'under',
	        	 tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{fundName} - <b>{fundCode}</b><br/></div>', 	'</tpl>'),
	        	 displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{fundName}', '</tpl>'),
	        	 listeners : {
	        		 select : {
	        			 fn : function(combo, value) {
	        				 var tempInsTypeCmb = Ext.ComponentQuery.query('#insDateSetInsTypeCmb')[0];
	        				 tempInsTypeCmb.clearValue();
	        				 tempInsTypeCmb.disable();
	        				 Ext.data.StoreManager.lookup('insDateSetCpnDtsStore').removeAll();
	        				 var tempInsCodeCmb = Ext.ComponentQuery.query('#insDateSetInsCodeCmb')[0];
	        				 tempInsCodeCmb.clearValue();
	        				 tempInsCodeCmb.disable();
	        				 Ext.ComponentQuery.query('#insDateSetMaturityDt')[0].reset();
	        				 Ext.ComponentQuery.query('#insDateSetIssueDt')[0].reset();
	        				 Ext.ComponentQuery.query('#insDateSetActionCmb')[0].clearValue();
	        				 Ext.ComponentQuery.query('#insDateSetCpnDtsPnl')[0].disable();
        					 Ext.ComponentQuery.query('#insDateSetCpnDtsPnl')[0].hide();
        					 Ext.ComponentQuery.query('#insDateSetFlotRtsPnl')[0].disable();
        					 Ext.ComponentQuery.query('#insDateSetFlotRtsPnl')[0].hide();
        					 Ext.ComponentQuery.query('#insDateSetBenchMark')[0].reset();
        					 Ext.ComponentQuery.query('#insDateSetResetPeriod')[0].reset();
        					 Ext.ComponentQuery.query('#insDateSetFloor')[0].reset();
        					 Ext.ComponentQuery.query('#insDateSetCeiling')[0].reset();
        					 Ext.data.StoreManager.lookup('insDateSetFloatingRtsStore').removeAll();
	        				 
	        				 var tempFundStore = Ext.data.StoreManager.lookup('insDateSetFundStore');	        				 
	        				 var lastUpdated = tempFundStore.getAt(tempFundStore.find('id', combo.getValue())).get('updateDate');
	        				 Ext.ComponentQuery.query('#insDateSetCpnDts')[0].setMinValue(Ext.Date.add(lastUpdated, Ext.Date.DAY,1));
	        				 Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].setMinValue(Ext.Date.add(lastUpdated, Ext.Date.DAY,1));
	        				 	        				 
	        				 Ext.ComponentQuery.query('#insDateSetFundLastUpdateLbl')[0].setText('Fund Last Updated on '+lastUpdated);
	        				 
	        				 var tempInsTypeStore = Ext.data.StoreManager.lookup('insDateSetInsTypeStore');
	        				 tempInsTypeStore.removeAll();
	        				 var tempInsCodesStore = Ext.data.StoreManager.lookup('insDateSetInsCodeStore');
	        				 tempInsCodesStore.removeAll();
	        				 Ext.Ajax.request({
	        					 url : 'fundInsTypesForDealType.action',
	        					 params : {
	        						 queryOne : combo.getValue(),
	        						 queryTwo : "PURCH",
	        					 },
	        					 success : function(response) {
	        						 var obj = Ext.decode(response.responseText);
	        						 tempInsTypeStore.loadRawData(obj.insTypes);
	        					 },
	        					 failure : function(response){
	        						 Ext.Msg.alert('Error!', 'Failed to load Instrument Types : '+response);
	        					 },
	        				 });
	        				 
	        				 Ext.Ajax.request({
	        					 url : 'InInsCodesForFund.action',
	        					 params : {
	        						 queryOne : combo.getValue(),
	        					 },
	        					 success : function(response) {
	        						 var obj = Ext.decode(response.responseText);
	        						 var arrayLength = obj.insCodes.length;
	        							for (var i = 0; i < arrayLength; i++) {
	        								tempInsCodesStore.add(
	        							    		{
	        							    			id				: obj.insCodes[i].id,
	        							    			instrumentCode	: obj.insCodes[i].instrumentCode,
	        							    			instrumentType	: obj.insCodes[i].instrumentType.instrumentName,
	        							    			issueDate		: obj.insCodes[i].issueDate,
	        							    			maturityDate	: obj.insCodes[i].maturityDate,	        							    			
	        							    		});
	        							}
	        						}
	        					});
	        			 }
	        		 }
	        	 },
			 },
	         {
	        	 xtype : 'combo',
	        	 fieldLabel : 'Action',
	        	 displayField : 'action',
	        	 flex : 1,
	        	 editable : false,
	        	 padding : '0 5 0 5',
	        	 queryMode : 'local',
	        	 store : actionStore,
	        	 id : 'insDateSetActionCmb',
	        	 listeners : {
	        		 select : {
	        			 fn : function(combo, value) {
	        				 var tempInsType = Ext.ComponentQuery.query('#insDateSetInsTypeCmb')[0];
	        				 var tempInsCode = Ext.ComponentQuery.query('#insDateSetInsCodeCmb')[0];
	        			
	        				 tempInsType.clearValue();
	        				 tempInsType.enable();
	        				 Ext.data.StoreManager.lookup('insDateSetCpnDtsStore').removeAll();
	        				 tempInsCode.clearValue();
	        				 tempInsCode.disable();
	        				 Ext.ComponentQuery.query('#insDateSetMaturityDt')[0].reset();
	        				 Ext.ComponentQuery.query('#insDateSetIssueDt')[0].reset();
	        				 
	        				 var tempInsTypeStore = Ext.data.StoreManager.lookup('insDateSetInsTypeStore');
	        				 tempInsTypeStore.clearFilter(true);
	        				 if(combo.getValue()==='Floating Rate Reset'){
	        					 Ext.ComponentQuery.query('#insDateSetCpnDtsPnl')[0].disable();
	        					 Ext.ComponentQuery.query('#insDateSetCpnDtsPnl')[0].hide();
	        					 Ext.ComponentQuery.query('#insDateSetFlotRtsPnl')[0].show();
	        					 Ext.ComponentQuery.query('#insDateSetFlotRtsPnl')[0].disable();
	        					 Ext.ComponentQuery.query('#insDateSetBenchMark')[0].reset();
	        					 Ext.ComponentQuery.query('#insDateSetResetPeriod')[0].reset();
	        					 Ext.ComponentQuery.query('#insDateSetFloor')[0].reset();
	        					 Ext.ComponentQuery.query('#insDateSetCeiling')[0].reset();
	        					 Ext.data.StoreManager.lookup('insDateSetFloatingRtsStore').removeAll();
	        					 
	        					 tempInsTypeStore.filter(
		 									[ Ext.create('Ext.util.Filter', { filterFn: function(item) {
		 										return (item.get("interestRate")=='V');},
		 										root: 'data' })
		 									]);
	        					 if(tempInsTypeStore.getCount()==0){
	        						 Ext.Msg.alert('Error', 'No Floating Rated Instrument Types Found with this Fund');
	        					 }
	        				 }else if(combo.getValue()==='Coupon Date Reset'){
	        					 Ext.ComponentQuery.query('#insDateSetFlotRtsPnl')[0].disable();
	        					 Ext.ComponentQuery.query('#insDateSetFlotRtsPnl')[0].hide();
	        					 Ext.ComponentQuery.query('#insDateSetBenchMark')[0].reset();
	        					 Ext.ComponentQuery.query('#insDateSetResetPeriod')[0].reset();
	        					 Ext.ComponentQuery.query('#insDateSetFloor')[0].reset();
	        					 Ext.ComponentQuery.query('#insDateSetCeiling')[0].reset();
	        					 Ext.data.StoreManager.lookup('insDateSetFloatingRtsStore').removeAll();
	        					 Ext.ComponentQuery.query('#insDateSetCpnDtsPnl')[0].show();
	        					 Ext.ComponentQuery.query('#insDateSetCpnDtsPnl')[0].disable();
	        					 
	        					 tempInsTypeStore.filter(
		 									[ Ext.create('Ext.util.Filter', { filterFn: function(item) {
		 										return (item.get("couponAvailability")==2);},
		 										root: 'data' })
		 									]);
	        					 if(tempInsTypeStore.getCount()==0){
	        						 Ext.Msg.alert('Error', 'No Coupon Available Instrument Types Found with this Fund');
	        					 }
	        				 }else{
	        					 Ext.Msg.alert('Error', 'Invalid Action!');	        					 
	        				 }
	        			 }	        					
	        		 }
	        	 },
	         }
	         	]
		},
		{
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ 
	         {
	        	 xtype : 'combo',
	        	 name : 'instrumentType',
	        	 fieldLabel : 'Instrument Type',
	        	 store : Ext.data.StoreManager.lookup('insDateSetInsTypeStore'),
	        	 valueField : 'instrumentName',
	        	 displayField : 'instrumentName',
	        	 queryMode : 'local',
	        	 flex : 1,
	        	 id : 'insDateSetInsTypeCmb',
	        	 padding : '0 5 0 5',
	        	 autoScroll : false,
	        	 allowBlank : false,
	        	 disabled : true,
	        	 msgTarget : 'under',
	        	 listeners : {
	        		 select : {
	        			 fn : function(combo, value) {
	        				 var tempInsCodes = Ext.data.StoreManager.lookup('insDateSetInsCodeStore');
	        				 Ext.ComponentQuery.query('#insDateSetInsCodeCmb')[0].clearValue();
	        				 Ext.ComponentQuery.query('#insDateSetMaturityDt')[0].reset();
	        				 Ext.ComponentQuery.query('#insDateSetIssueDt')[0].reset();
	        				 Ext.ComponentQuery.query('#insDateSetInsCodeCmb')[0].enable();
	        				 Ext.ComponentQuery.query('#insDateSetBenchMark')[0].reset();
        					 Ext.ComponentQuery.query('#insDateSetResetPeriod')[0].reset();
        					 Ext.ComponentQuery.query('#insDateSetFloor')[0].reset();
        					 Ext.ComponentQuery.query('#insDateSetCeiling')[0].reset();
        					 Ext.data.StoreManager.lookup('insDateSetFloatingRtsStore').removeAll();
	        				 tempInsCodes.clearFilter(true);
	        				 tempInsCodes.filter(
	 									[ Ext.create('Ext.util.Filter', { filterFn: function(item) {
	 										return (item.get("instrumentType")==combo.getValue());},
	 										root: 'data' })
	 									]);
	        				 if(tempInsCodes.getCount()==0){
	        					 Ext.Msg.alert('Error', 'No Instruments Found!');
	        				 }

	        				 Ext.ComponentQuery.query('#insDateSetFlotRtsPnl')[0].disable();
	        				 Ext.ComponentQuery.query('#insDateSetCpnDtsPnl')[0].disable();
	        			 }
	        		 }
	        	 },
	         },
	         {
	        	 xtype : 'combo',
	        	 name : 'instrumentId',
	        	 fieldLabel : 'Instrument Code',
	        	 store : Ext.data.StoreManager.lookup('insDateSetInsCodeStore'),
	        	 valueField : 'id',
	        	 displayField : 'instrumentCode',
	        	 queryMode : 'local',
	        	 flex : 1,
	        	 id : 'insDateSetInsCodeCmb',
	        	 padding : '0 5 0 5',
	        	 autoScroll : false,
	        	 allowBlank : false,
	        	 disabled : true,
	        	 msgTarget : 'under',
	        	 listeners : {
	        		 select : {
	        			 fn : function(combo, value) {
	        				 var action = Ext.ComponentQuery.query('#insDateSetActionCmb')[0].getValue();	        					 
	        				 if(action=='Coupon Date Reset'){
	        					 var loadingMask = Ext.getCmp('insDateSetCpnDtsPnl');
		        				 loadingMask.setLoading('Loading Coupon Dates...', true);
		        				 Ext.Ajax.request({
		        					 url : 'queryCouponDates.action',
		        					 params : {
		        						 queryOne : combo.getValue(),
		        					 },
		        					 success : function(response) {
		        						 var obj = Ext.decode(response.responseText);
		        						 if(obj.couponDates!=null && obj.couponDates!=''){
		        							 var cpnDtsArray = obj.couponDates.split(";");
		        							 var cpnDtStoreLocal = Ext.data.StoreManager.lookup('insDateSetCpnDtsStore');
		        							 cpnDtStoreLocal.removeAll();
		        							 var i=0;
		        							 for (i = 0; i < cpnDtsArray.length-1; i++) {
		        								 cpnDtStoreLocal.add({
		        									 couponDate : cpnDtsArray[i],
		        								 });
		        							 }
		        							 cpnDtStoreLocal.sort('couponDate', 'ASC');
		        						 }
		        						 Ext.ComponentQuery.query('#insDateSetFlotRtsPnl')[0].disable();
			        					 Ext.ComponentQuery.query('#insDateSetCpnDtsPnl')[0].enable();
		        						 loadingMask.setLoading(false);
		        					 },
		        					 failure : function(response){
		        						 loadingMask.setLoading(false);
		        						 Ext.Msg.alert('Error!', 'Failed to load Fund List : '+response);
		        					 },
		        				 });	        					 
	        				 }else if(action=='Floating Rate Reset'){
	        					 var loadingMask = Ext.getCmp('insDateSetFlotRtsPnl');
		        				 loadingMask.setLoading('Loading Floating Rates...', true);
		        				 Ext.Ajax.request({
		        					 url : 'queryFloatingRates.action',
		        					 params : {
		        						 queryOne : combo.getValue(),
		        					 },
		        					 success : function(response) {
		        						 var obj = Ext.decode(response.responseText);
		        						 Ext.ComponentQuery.query('#insDateSetBenchMark')[0].setValue(obj.benchMark);
		        						 Ext.ComponentQuery.query('#insDateSetResetPeriod')[0].setValue(obj.resetPeriod);
		        						 Ext.ComponentQuery.query('#insDateSetFloor')[0].setValue(obj.floor);
		        						 Ext.ComponentQuery.query('#insDateSetCeiling')[0].setValue(obj.ceiling);
		        						 var flotRatetb = Ext.ComponentQuery.query('#insDateSetFloatingRate')[0];
		        						 flotRatetb.setMaxValue(obj.ceiling);
		        						 flotRatetb.setMinValue(obj.floor);
		        						 var flotingRtStoreLocal = Ext.data.StoreManager.lookup('insDateSetFloatingRtsStore');
	        							 flotingRtStoreLocal.removeAll();
		        						 if(obj.floatingRates!=null && obj.floatingRates!=''){
		        							 var flotRtsArray = obj.floatingRates.split(";");
		        							 var i=0;
		        							 for (i = 0; i < flotRtsArray.length-1; i++) {
		        								 var recordAr = flotRtsArray[i].split('|');
		        								 flotingRtStoreLocal.add({
		        									 startDate		: recordAr[0],
		        									 resetDate		: recordAr[2],
		        									 floatingRate	: recordAr[1]
		        								 });
		        							 }
		        							 flotingRtStoreLocal.sort('resetDate', 'ASC');
		        							 Ext.ComponentQuery.query('#insDateSetFloatResetLbl')[0].setText('Next Reset Date: '+flotingRtStoreLocal.last().get('resetDate'));
		        							 Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].setMaxValue(flotingRtStoreLocal.last().get('resetDate'));
		        							 Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].setValue(flotingRtStoreLocal.last().get('resetDate'));
		        						 }
		        						 //Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].setMaxValue(Ext.Date.parse(obj.resetDate, 'd/M/Y'));
		        						 Ext.ComponentQuery.query('#insDateSetFlotRtsPnl')[0].enable();
			        					 Ext.ComponentQuery.query('#insDateSetCpnDtsPnl')[0].disable();
		        						 loadingMask.setLoading(false);
		        					 },
		        					 failure : function(response){
		        						 loadingMask.setLoading(false);
		        						 Ext.Msg.alert('Error!', 'Failed to load Fund List : '+response);
		        					 },
		        				 });		        				 
	        				 }
	        				 
	        				 var tempInsCodeStore = Ext.data.StoreManager.lookup('insDateSetInsCodeStore');
	        				 var tempInsId = Ext.ComponentQuery.query('#insDateSetInsCodeCmb')[0].getValue();
	        				 var insIssueDate = tempInsCodeStore.getAt(tempInsCodeStore.find('id', tempInsId)).get('issueDate');
	        				 Ext.ComponentQuery.query('#insDateSetIssueDt')[0].setValue(insIssueDate);
	        				 var insMaturityDate = tempInsCodeStore.getAt(tempInsCodeStore.find('id', tempInsId)).get('maturityDate');
	        				 Ext.ComponentQuery.query('#insDateSetMaturityDt')[0].setValue(insMaturityDate);
	        			 }
	        		 }
	        	 },
	         }
			         ]		
		},
		{	
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [
			{
				xtype : 'datefield',
				fieldLabel : 'Issue Date',
				id : 'insDateSetIssueDt',
				flex : 1,
				padding : '0 5 0 5',
				msgTarget : 'under',
				format : 'd/m/Y',
				emptyText : 'DD/MM/YYYY',
				disabled : true,
			},
			{
				xtype : 'datefield',
				fieldLabel : 'Maturity Date',
				id : 'insDateSetMaturityDt',
				flex : 1,
				padding : '0 5 0 5',
				msgTarget : 'under',
				format : 'd/m/Y',
				emptyText : 'DD/MM/YYYY',
				disabled : true,
			}
	         
			        ]
		},
		{	
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [
				{
					xtype : 'label',
					id : 'insDateSetFundLastUpdateLbl',
					padding : '0 5 0 5',
				}	         
			]
		}
		]
	});

	return fieldSet1;
};



InsDateSet.getFieldSet2 = function() {
	
	var insCpnDtStore = Ext.create('Ext.data.Store', {
		storeId:'insDateSetCpnDtsStore',
		fields : [ {
			name : 'couponDate',
			type : 'date',
			dateFormat : 'd/m/Y'
		} ],
		sortInfo: {
		    field: 'couponDate',
		    direction: 'ASC', // or 'DESC' (case sensitive for local sorting)
		},
	});
	
	var fieldSet2 = Ext.create('Ext.panel.Panel', {
		title : 'Coupon Dates',
		id : 'insDateSetCpnDtsPnl',
		disabled : true,
		hidden : true,
		frame : true,
		layout : 'hbox',
		defaults : {
			anchor : '100%'
		},
		items : [		         
		{
			xtype : 'datefield',
			fieldLabel : 'Coupon Dates',
			id : 'insDateSetCpnDts',
			flex : 1,
			padding : '0 5 0 5',
			labelWidth : 115,
			msgTarget : 'under',
			format : 'd/m/Y',
			emptyText : 'DD/MM/YYYY',
			listeners : {
				change : {
					fn : function(object, newVal, oldVal) {
						var tempInsCodeStore = Ext.data.StoreManager.lookup('insDateSetInsCodeStore');
						var tempInsId = Ext.ComponentQuery.query('#insDateSetInsCodeCmb')[0].getValue();
						var insIssueDate = tempInsCodeStore.getAt(tempInsCodeStore.find('id', tempInsId)).get('issueDate');
						var tempFundId = Ext.ComponentQuery.query('#insDateSetFundCmb')[0].getValue();
						var tempFundStore = Ext.data.StoreManager.lookup('insDateSetFundStore');
						var lastUpdated = tempFundStore.getAt(tempFundStore.find('id', tempFundId)).get('updateDate');
						var insMaturityDate = tempInsCodeStore.getAt(tempInsCodeStore.find('id', tempInsId)).get('maturityDate');
						var recordIndex = insCpnDtStore.findBy(function(record, id) {
							if (newVal!=null && (record.get('couponDate').getTime() == newVal.getTime())) {
								return true;
							}
							return false;
						});
						if (recordIndex != -1) {
							Ext.MessageBox.alert('Error!', 'Duplicate Entry!!!');
						}else if(newVal==null){
							console.log("Null value for date field");								
						}else if(newVal<insIssueDate || newVal>insMaturityDate){
							Ext.MessageBox.alert('Error!', 'Coupon Date should be within the Deal Period!');
						}else if(newVal<=lastUpdated){
							Ext.MessageBox.alert('Error!', 'Coupon Date should be greater than: '+lastUpdated);
						}else {
							insCpnDtStore.add({
								couponDate : Ext.util.Format.date(newVal, 'd/m/Y')
							});
							insCpnDtStore.sort('couponDate', 'ASC'); 
						}
					}
				}
			}
		}, Ext.create('Ext.grid.Panel', {
			width : 100,
			height : 180,
			flex : 1,
			store : insCpnDtStore,
			id : 'insDateSetDtStore',
			autoScroll : true,
			columns : [ {
				xtype : 'datecolumn',
				header : 'Coupon Dates',
				dataIndex : 'couponDate',
				format : 'd/m/Y',
				flex : 1
			} ],
			bbar : [ {
				xtype : 'button',
				text : 'Remove',
				handler : function() {
					var tempFundId = Ext.ComponentQuery.query('#insDateSetFundCmb')[0].getValue();					
					var tempFundStore = Ext.data.StoreManager.lookup('insDateSetFundStore');
					var lastUpdated = tempFundStore.getAt(tempFundStore.find('id', tempFundId)).get('updateDate');
					var pCpnDtStore = Ext.ComponentQuery.query('#insDateSetDtStore')[0];
					var sm = pCpnDtStore.getSelectionModel();
					var sel = sm.getSelection();
					var i =0;
					for (i = 0; i < sel.length; i++) {
						if(sel[i].get("couponDate")>lastUpdated){
							pCpnDtStore.store.remove(sel[i]);
						}else{
							Ext.Msg.alert('Error', 'Cannot Remove values before '+lastUpdated);
						}
					}
				}
			} ]
		})
		]
	});

	return fieldSet2;
};



InsDateSet.getFieldSet3 = function() {
	
	var insFloatDtStore = Ext.create('Ext.data.Store', {
		storeId:'insDateSetFloatingRtsStore',
		fields : [
		          {	name : 'startDate',		type : 'date',		dateFormat : 'd/m/Y'	},
		          {	name : 'resetDate',		type : 'date',		dateFormat : 'd/m/Y'	},
		          {	name : 'floatingRate',	type : 'float',								}
		         ],
		sortInfo: {
		    field: 'resetDate',
		    direction: 'ASC', //'DESC'
		},
	});
	
	
var fieldSet3 = Ext.create('Ext.panel.Panel', {
		title : 'Floating Rates',
		id : 'insDateSetFlotRtsPnl',
		disabled : true,
		hidden : true,
		frame : true,
		defaults : {
			anchor : '100%',
			//flex : 1,
		},
		layout: {
			type: 'vbox',
			align: 'stretch',  // Child items are stretched to full width
		},
		items : [
	 		{
				xtype : 'fieldcontainer',
				layout : 'hbox',
				items : [
				{
					xtype : 'textfield',
					padding : '0 5 0 5',
					allowBlank : false,
					id : 'insDateSetBenchMark',
					fieldLabel : 'Bench Mark',
					flex : 1,
					//fieldStyle : "text-align:right;",
					disabled : true,				
				},
				{
					xtype : 'textfield',
					padding : '0 5 0 5',
					allowBlank : false,
					id : 'insDateSetResetPeriod',
					fieldLabel : 'Reset Period',
					flex : 1,
					//fieldStyle : "text-align:right;",
					disabled : true,				
				}
				]
			},
			{
				xtype : 'fieldcontainer',
				layout : 'hbox',
				items : [
				{
					xtype : 'textfield',
					padding : '0 5 0 5',
					allowBlank : false,
					id : 'insDateSetFloor',
					fieldLabel : 'Floor',
					flex : 1,
					disabled : true,				
				},
				{
					xtype : 'textfield',
					padding : '0 5 0 5',
					allowBlank : false,
					id : 'insDateSetCeiling',
					fieldLabel : 'Ceiling',
					flex : 1,
					disabled : true,				
				}				
				]
			},
			{
				xtype : 'fieldcontainer',
				layout : 'hbox',
				items : [
					{
						xtype : 'numberfield',
						minValue : 0,
						maxValue : 100,
						decimalPrecision: 4,
						padding : '0 5 0 5',
						fieldLabel : 'Rate',
						flex : 1,
						id:'insDateSetFloatingRate',
					},
					{
						xtype : 'datefield',
						fieldLabel : 'Starting Date',
						id : 'insDateSetFlotingDt',
						flex : 1,
						padding : '0 5 0 5',
						format : 'd/m/Y',
						emptyText : 'DD/MM/YYYY',
						listeners : {
							'change' : {
								fn : function(field, newVal, oldVal){
									if(newVal!=null){
										var rstPeriod = Ext.ComponentQuery.query('#insDateSetResetPeriod')[0].getValue();
						        		var rstDate = Ext.Date.add(newVal, Ext.Date.DAY, new Number(rstPeriod));
						        		var tempResetDtField = Ext.ComponentQuery.query('#insDateSetResetDt')[0];
						        		var matDateTemp = Ext.ComponentQuery.query('#insDateSetMaturityDt')[0].getValue();
						        		if(matDateTemp>rstDate){
						        			tempResetDtField.setValue(rstDate);
						        		}else{
						        			tempResetDtField.setValue(matDateTemp);
						        		}
									}
								}
							}
						}
					}		
				]			
			},
			{
				xtype : 'fieldcontainer',
				layout : 'hbox',
				items : [
				    {
						xtype : 'checkboxfield',
						boxLabel : 'Adjust Reset Date',
						id : 'insDateSetManualResetCb',
						flex : 1,
						padding : '0 5 0 5',
						listeners : {
							change : function(field, newVal) {
								if (newVal) {
									Ext.ComponentQuery.query('#insDateSetResetDt')[0].enable();
								}else{
									Ext.ComponentQuery.query('#insDateSetResetDt')[0].disable();								
									var newStartDt = Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].getValue();
									if(newStartDt!=null){
										var rstPeriod = Ext.ComponentQuery.query('#insDateSetResetPeriod')[0].getValue();
						        		var rstDate = Ext.Date.add(newStartDt, Ext.Date.DAY, new Number(rstPeriod));
						        		var tempResetDtField = Ext.ComponentQuery.query('#insDateSetResetDt')[0];
						        		var matDateTemp = Ext.ComponentQuery.query('#insDateSetMaturityDt')[0].getValue();
						        		if(matDateTemp>rstDate){
						        			tempResetDtField.setValue(rstDate);
						        		}else{
						        			tempResetDtField.setValue(matDateTemp);
						        		}
									}
								}
							}
						}
				    },
					{
						xtype : 'datefield',
						fieldLabel : 'Reset Date',
						id : 'insDateSetResetDt',
						disabled : true,
						flex : 1,
						padding : '0 5 0 5',
						format : 'd/m/Y',
						emptyText : 'DD/MM/YYYY'
					}
				]			
			
			},
			{	
				xtype : 'fieldcontainer',
				layout : 'hbox',
				items : [
					{
						xtype : 'label',
						id : 'insDateSetFloatResetLbl',
						padding : '0 5 0 5',
					}	         
				]
			}
		, Ext.create('Ext.grid.Panel', {
			width : 100,
			height : 180,
			flex : 1,
			store : insFloatDtStore,
			id : 'insDateSetFloatRtPanel',
			autoScroll : true,
			columns : [
						{
							   xtype : 'numbercolumn',
							   header : 'Floating Rate',
							   dataIndex : 'floatingRate',
							   format : '0,000.0000',
							   minValue : 0,
							   flex : 1,
						},
			            {
							xtype : 'datecolumn',
							header : 'Starting Date',
							dataIndex : 'startDate',
							format : 'd/m/Y',
							flex : 1,
			            },
			            {
							xtype : 'datecolumn',
							header : 'Reset Date',
							dataIndex : 'resetDate',
							format : 'd/m/Y',
							flex : 1,
			            }
			],
			tbar : [
			        '->',
			        {
			        	text : 'Add',
			        	handler : function() {
			        		var strtDate = Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].getValue();
			        		var rstPeriod = Ext.ComponentQuery.query('#insDateSetResetPeriod')[0].getValue();
			        		var rstDateCal=null;
			        		var resetDateVal=null;
			        		if(strtDate!=null){
			        			rstDateCal= Ext.Date.add(strtDate, Ext.Date.DAY, new Number(rstPeriod));
				        		Ext.ComponentQuery.query('#insDateSetResetDt')[0].enable();
				        		resetDateVal = Ext.ComponentQuery.query('#insDateSetResetDt')[0].getValue();
				        		if(resetDateVal==null){
				        			resetDateVal = rstDateCal;
				        		}
			        		}
			        		
			        		var rate = Ext.ComponentQuery.query('#insDateSetFloatingRate')[0].getValue();
			        		var floor = Ext.ComponentQuery.query('#insDateSetFloor')[0].getValue();
			        		var ceiling = Ext.ComponentQuery.query('#insDateSetCeiling')[0].getValue();
			        		insFloatDtStore.sort('startDate', 'ASC');
			        		var lastRec = insFloatDtStore.last();

							var tempInsCodeStore = Ext.data.StoreManager.lookup('insDateSetInsCodeStore');
							var tempInsId = Ext.ComponentQuery.query('#insDateSetInsCodeCmb')[0].getValue();
							var insIssueDate = tempInsCodeStore.getAt(tempInsCodeStore.find('id', tempInsId)).get('issueDate');
							var tempFundId = Ext.ComponentQuery.query('#insDateSetFundCmb')[0].getValue();
							var tempFundStore = Ext.data.StoreManager.lookup('insDateSetFundStore');
							var lastUpdated = tempFundStore.getAt(tempFundStore.find('id', tempFundId)).get('updateDate');
							
							var insMaturityDate = tempInsCodeStore.getAt(tempInsCodeStore.find('id', tempInsId)).get('maturityDate');
							var recordIndex = 0;
							if(strtDate!=null){
								recordIndex = insFloatDtStore.findBy(function(record, id) {
									if ((record.get('startDate').getTime() == strtDate.getTime())) {
										return true;
									}
									return false;
								});
							}
							
							if(strtDate==null){
								Ext.Msg.alert('Error', 'Fields incomplete!');
							}else if (recordIndex != -1) {
								Ext.MessageBox.alert('Error!', 'Duplicate Entry!!!');
							}else if(strtDate<insIssueDate || strtDate>insMaturityDate){
								Ext.MessageBox.alert('Error!', 'Start Date should be within the Deal Period!');
							}else if(strtDate<=lastUpdated){
								Ext.MessageBox.alert('Error!', 'Start Date should be greater than: '+lastUpdated);
							}else if(rate<floor){
								Ext.MessageBox.alert('Error!', 'Rate should be greater than Floor Value!');
							}else if(rate>ceiling){
								Ext.MessageBox.alert('Error!', 'Rate should be less than Ceiling Value!');
							}else if(lastRec!=undefined && strtDate>lastRec.get('resetDate')){
								Ext.MessageBox.alert('Error!', 'Start Date cannot be greater than: '+lastRec.get('resetDate'));
							}else if(lastRec!=undefined && strtDate<lastRec.get('startDate')){
								Ext.MessageBox.alert('Error!', 'Start Date overlaps with existing Start Date: '+lastRec.get('startDate'));
							}else if(rstDateCal<resetDateVal){
								Ext.MessageBox.alert('Error!', 'Cannot reset after : '+rstDateCal);
							}else {
								insFloatDtStore.add({
									startDate		: strtDate,
									resetDate		: resetDateVal,
									floatingRate	: rate,
								});
								
								insFloatDtStore.sort('startDate', 'ASC');
								Ext.ComponentQuery.query('#insDateSetFloatResetLbl')[0].setText('Next Reset Date: '+insFloatDtStore.last().get('resetDate'));
								Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].setMaxValue(insFloatDtStore.last().get('resetDate'));
								Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].setValue(insFloatDtStore.last().get('resetDate'));
								Ext.ComponentQuery.query('#insDateSetFloatingRate')[0].reset();								
								Ext.ComponentQuery.query('#insDateSetResetDt')[0].reset();
								Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].reset();
								Ext.ComponentQuery.query('#insDateSetManualResetCb')[0].reset();
								Ext.ComponentQuery.query('#insDateSetResetDt')[0].disable();
							}
			        	}
			        },
			        {
			        	xtype : 'button',
			        	text : 'Remove',
			        	handler : function() {
			        		var insFloatDtStorePanel = Ext.ComponentQuery.query('#insDateSetFloatRtPanel')[0];
			        		var sm = insFloatDtStorePanel.getSelectionModel();
			        		var sel = sm.getSelection();
			        		var i =0;
			        		for (i = 0; i < sel.length; i++) {
			        			var selStartDate = sel[i].get("startDate");			        			
			        			insFloatDtStore.sort('startDate', 'ASC');
				        		var lastSartDate = insFloatDtStore.last().get('startDate');
				        		if (lastSartDate!=null && (selStartDate.getTime() == lastSartDate.getTime())) {
				        			var tempFundId = Ext.ComponentQuery.query('#insDateSetFundCmb')[0].getValue();
					        		var tempFundStore = Ext.data.StoreManager.lookup('insDateSetFundStore');
					        		var lastUpdated = tempFundStore.getAt(tempFundStore.find('id', tempFundId)).get('updateDate');
					        		
				        			if(sel[i].get("startDate")>lastUpdated){
				        				insFloatDtStore.remove(sel[i]);
				        				insFloatDtStore.sort('startDate', 'ASC');
				        				if(insFloatDtStore.last()==undefined){
				        					 var tempInsCodeStore = Ext.data.StoreManager.lookup('insDateSetInsCodeStore');
					        				 var tempInsId = Ext.ComponentQuery.query('#insDateSetInsCodeCmb')[0].getValue();
					        				 var insIssueDate = tempInsCodeStore.getAt(tempInsCodeStore.find('id', tempInsId)).get('issueDate');
					        				 Ext.ComponentQuery.query('#insDateSetFloatResetLbl')[0].setText('Next Reset Date: '+insIssueDate);
					        				 Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].setMaxValue(insIssueDate);
					        				 Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].setValue(insIssueDate);
				        				}else{
				        					Ext.ComponentQuery.query('#insDateSetFloatResetLbl')[0].setText('Next Reset Date: '+insFloatDtStore.last().get('resetDate'));
											Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].setMaxValue(insFloatDtStore.last().get('resetDate'));
											Ext.ComponentQuery.query('#insDateSetFlotingDt')[0].setValue(insFloatDtStore.last().get('resetDate'));
				        				}
				        			}else{
				        				Ext.Msg.alert('Error', 'Cannot Remove values before '+lastUpdated);
				        			}
								}else{
									Ext.Msg.alert('Cannot Delete', 'First Remove the Last Record');
								}			        			
			        		}
			        	}
			        }
			       ],
		})
		]
	});
	
	return fieldSet3;

	
	
};





InsDateSet.getCenterPanel = function() {

	var filedset1 = InsDateSet.getFieldSet1();
	var filedset2 = InsDateSet.getFieldSet2();
	var filedset3 = InsDateSet.getFieldSet3();


	var formPanel =  Ext.create('Ext.form.FormPanel', {
		id : 'insDateSetFormPanel',
		frame : true,
		autoScroll : true,
		defaults : {
			anchor : '72%',
		},
		title : 'Coupon Dates and Floating Rate Reset',
		items : [ filedset1, filedset2, filedset3],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				Ext.ComponentQuery.query('#insDateSetFundLastUpdateLbl')[0].setText('');
				App.Core.setScreen(InsDateSet.getCenterPanel());
			}
		}, {
			text : 'Save',
			id : 'insDateSetSaveBtn',
			itemId : 'saveButton',
			handler : function() {
				var form = this.up('form').getForm();
				formPanel.setLoading('Saving...');

				if (form.isValid()) {
					
					var action = Ext.ComponentQuery.query('#insDateSetActionCmb')[0].getValue();
					if(action=='Coupon Date Reset'){
						form.url = 'updateCpnDts.action';
						
						var couponDates = '';
						Ext.data.StoreManager.lookup('insDateSetCpnDtsStore').each(function(r) {
							couponDates += Ext.util.Format.date(r.get('couponDate'))+';';
						});
						form.submit({						
							params : {
								'couponDates'	: couponDates,
								//'couponDates'	: Ext.util.Format.date(valueDtField.getValue()),
							},
							success : function(form, action) {
								Ext.ComponentQuery.query('#insDateSetFundLastUpdateLbl')[0].setText('');
								Ext.Msg.alert('Success', 'Coupon Dates Updated.');
								formPanel.setLoading(false);
								Ext.data.StoreManager.lookup('insDateSetCpnDtsStore').removeAll();
								Ext.ComponentQuery.query('#insDateSetFundLastUpdateLbl')[0].setText('');
								App.Core.setScreen(InsDateSet.getCenterPanel());								
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', 'There is some error returned from the server.<br>'+action.result.status);
								formPanel.setLoading(false);
							}
						});						
					}else if(action=='Floating Rate Reset'){
						
						form.url = 'updateFlotinRts.action';
						var floatingRates = '';
						
						var insFloatDtStore = Ext.data.StoreManager.lookup('insDateSetFloatingRtsStore');
						insFloatDtStore.sort('startDate', 'ASC');
						insFloatDtStore.each(function(r) {
							floatingRates += Ext.util.Format.date(r.get('startDate'))+'|'+Ext.util.Format.date(r.get('resetDate'))+'|'+r.get('floatingRate')+';';
						});
						
						form.submit({						
							params : {
								'floatingRates'	: floatingRates,
							},
							success : function(form, action) {
								Ext.ComponentQuery.query('#insDateSetFundLastUpdateLbl')[0].setText('');
								
								Ext.Msg.alert('Success', 'Floating Rates Updated.');
								formPanel.setLoading(false);
								Ext.ComponentQuery.query('#insDateSetBenchMark')[0].reset();
								Ext.ComponentQuery.query('#insDateSetResetPeriod')[0].reset();
								Ext.ComponentQuery.query('#insDateSetFloor')[0].reset();
								Ext.ComponentQuery.query('#insDateSetCeiling')[0].reset();
								insFloatDtStore.removeAll();
								formPanel.setLoading(false);
								App.Core.setScreen(InsDateSet.getCenterPanel());								
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', 'There is some error returned from the server.<br>'+action.result.status);
								formPanel.setLoading(false);
							}
						});
					}else{
						Ext.Msg.alert('Error', 'Invalid Action!');
						formPanel.setLoading(false);
					}					
				}else{
					Ext.Msg.alert("Form Incomplete. Please check!");
				}
			}		
		}
		]
	});
	return formPanel;
};